/*
package com.anjiplus.template.gaea.business.modules.quartzReport.from;


import cn.hutool.core.map.MapUtil;
import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anjiplus.template.gaea.business.modules.datasettransform.service.IGroovyHandler;
import com.anjiplus.template.gaea.business.modules.quartzReport.task.SyncData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.context.ApplicationContext;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DemoGroovyHandler implements IGroovyHandler {

    @Override
    public List<JSONObject> transform(List<JSONObject> data) throws Exception {

        ApplicationContext applicaiton = ApplicationContext.getApplicaiton();

        HashMap<String, Object> formmap = new HashMap<>();
        HashMap<String, Object> curpagemap = new HashMap<>();
        curpagemap.put("pagesize", 20);
        curpagemap.put("curpage", 1);
        formmap.put("params", curpagemap);
        for( int  k=1 ; k <= 3 ;k++) {
            HashMap<String, Object> depmap = new HashMap<>();
            depmap.put("pagesize", 100);
            depmap.put("curpage", k);
            HashMap<String, Object> xinformmap = new HashMap<>();
            xinformmap.put("params", depmap);
            String body = sendRequest("http://xtoa.hbxtfd.cn/api/hrm/resful/getHrmdepartmentWithPage", JSONObject.toJSONString(xinformmap));
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONObject dataJSONObject = jsonObject.getJSONObject("data");
            JSONArray datalist = dataJSONObject.getJSONArray("dataList");
        }
        String body = sendRequest("http://xtoa.hbxtfd.cn/api/hrm/resful/getHrmUserInfoWithPage", JSONObject.toJSONString(formmap));
        String totalSizeString = JSONArray.parseObject(body).getJSONObject("data").getString("totalSize");
        curpagemap.put("pagesize", Integer.valueOf(totalSizeString));
        formmap.put("params", curpagemap);
        String Allbody = sendRequest("http://xtoa.hbxtfd.cn/api/hrm/resful/getHrmUserInfoWithPage", JSONObject.toJSONString(formmap));
        JSONArray dataList = JSONArray.parseObject(Allbody).getJSONObject("data").getJSONArray("dataList");
        //同步日志
        */
/*TBLoginLog tbLoginLog = new TBLoginLog();
        tbLoginLog.setCreatedTime(LocalDateTime.now());
        tbLoginLog.setOptionDesc("同步OA用户");
        tbLoginLog.setRequestUri("oauth");*//*

        int k=0;
        int t=0;
        for (int i = 0; i < dataList.size(); i++) {
            JSONObject shujuJSONObject = dataList.getJSONObject(i);
            //登录名
            Object workcode = shujuJSONObject.get("workcode");
            //人员名称
            Object lastname = shujuJSONObject.get("lastname");
            Object loginid = shujuJSONObject.get("loginid");
            Object mobile = shujuJSONObject.get("mobile");
            //人员编码 id
            Object id = shujuJSONObject.get("id");
            Object departmentid = shujuJSONObject.get("departmentid");
            QueryWrapper<UserInfo> UserWrapper = new QueryWrapper<>();
            UserWrapper.eq("userName", workcode);
            UserWrapper.eq("delete_state", 0);
//            List<UserInfo> userInfos = userInfoService.list(UserWrapper);
           */
/* if (userInfos.size() > 0) {
                if (StringUtils.isEmpty(loginid)){
                    UserInfo userInfo = userInfos.get(0);
                    if (userInfo.getUserState()!=0){
                        userInfo.setUserState(0);
                        userInfoService.updateById(userInfo);
                        t++;
                        System.out.println("关闭用户"+workcode+" "+lastname);
                    }
                }
                continue;
            }*//*

            System.out.println("新增"+workcode+"用户账号名字"+lastname);
            k++;
            // 3.创建用户表
            */
/*UserInfoForm userInfoForm = new UserInfoForm();
            String salt = String.format("%04d", new Random().nextInt(9999));
            userInfoForm.setSalt(salt);
            userInfoForm.setPassword(AesEncryptUtils.encrypt("p4HETBLkmy1pDM7usaq81g==", AesEncryptUtils.getKey() + salt));
            if (StringUtils.isEmpty(loginid)) {
                userInfoForm.setUserState(0);
            }else {
                userInfoForm.setUserState(1);
            }
            userInfoForm.setEmployeeCode(id.toString());
            userInfoForm.setNickName(lastname.toString());
            userInfoForm.setUserName(workcode.toString());*//*

            List<TBEmployee> tbEmployeeList = tBEmployeeService.list(new QueryWrapper<TBEmployee>() {{
                this.eq("staff_code", id);
                this.eq("delete_state", 0);

            }});
            if (tbEmployeeList.size()==0) {
                TBEmployee employee = new TBEmployee();
                employee.setCreatedTime(LocalDateTime.now());
                employee.setEmployeeCode(id.toString());
                employee.setEmployeeName(lastname.toString());
                employee.setEmployeeGender("1");
                employee.setEmployeeState(1);
                if (StringUtils.isEmpty(mobile)){
                    employee.setPhoneNum(mobile.toString());
                }
                employee.setStaffCode(id.toString());
                employee.setEmploymentStatus("1");
                tBEmployeeService.save(employee);
            }
            if (!StringUtils.isEmpty(departmentid)){
                TBPostInfoForm tbPostInfoForm = new TBPostInfoForm();
                tbPostInfoForm.setGroupCode("000000020");
                tbPostInfoForm.setCompanyCode("000000015");
                tbPostInfoForm.setCreateTime(LocalDateTime.now());
                tbPostInfoForm.setIsPartTimeJob("0");
                tbPostInfoForm.setEmployeeCode(id.toString());
                tbPostInfoForm.setDeptCode(departmentid.toString());
                tbPostInfoForm.setIsCurrent(0);
                tBPostInfoService.save(tbPostInfoForm);
            }
            int userId = userInfoService.saveById(userInfoForm);
            UserInfoRole userInfoRole = new UserInfoRole();
            userInfoRole.setRoleId(146);
            userInfoRole.setUserInfoId(userId);
            userInfoRoleService.save(userInfoRole);
            // 5.增加页面主题
            TBSkinChangingConfigurationForm tbSkinChangingConfiguration = new TBSkinChangingConfigurationForm();
            tbSkinChangingConfiguration.setColorconfig("#409EFF");
            tbSkinChangingConfiguration.setSkinconfig("1");
            tbSkinChangingConfiguration.setUserId(userId);
            tbSkinChangingConfiguration.setFormconfig("#409EFF");
            tbSkinChangingConfigurationService.save(tbSkinChangingConfiguration);
        }
        tbLoginLog.setExtFiled5("成功了"+k+"条，禁用了"+t+"条");
        tbLoginLog.setExtFiled6("200");
        tBLoginLogService.save(tbLoginLog);
        QueryWrapper<UserInfo> UserInfoWrapper = new QueryWrapper<>();
        UserInfoWrapper.eq("delete_state", 0);
        UserInfoWrapper.isNull("phone_num");
        List<UserInfo> userInfoList = userInfoService.list(UserInfoWrapper);
        if (userInfoList.size()>0){
            for (UserInfo userInfo : userInfoList) {
                try {
                    HashMap<String,Object> mmp = new HashMap<>();
                    mmp.put("name", userInfo.getUserName());
                    mmp.put("status", 1);
                    mmp.put("path", "/");
                    mmp.put("displayName", userInfo.getNickName());
                    mmp.put("userDirectoryId", "d01542c0-680a-11ee-a7c9-e186cf53b515");
                    List<TBEmployee> employeeList = tBEmployeeService.list(new QueryWrapper<TBEmployee>() {{
                        this.in("employee_code",userInfo.getEmployeeCode() );
                    }});
                    if (employeeList.size()>0){
                        if (!StringUtils.isEmpty( employeeList.get(0).getPhoneNum())){
                            mmp.put("phone", employeeList.get(0).getPhoneNum());
                            userInfo.setPhoneNum(employeeList.get(0).getPhoneNum());
                        }else {
                            userInfo.setPhoneNum("0");
                        }
                    }
                    Map hh = SyncData.getHeader("/api/v2/externalUser/create", null, mmp);
                    System.out.println("x-ca-sign:" + hh.get("x-ca-sign").toString());
                    System.out.println("x-ca-timestamp:" + hh.get("x-ca-timestamp").toString());
                    System.out.println("x-ca-key:" + hh.get("x-ca-key").toString());
                    System.out.println("x-ca-nonce:" + hh.get("x-ca-nonce").toString());
                    Map<Object, Object> head = MapUtil.builder().put("x-ca-sign", hh.get("x-ca-sign").toString()).put("x-ca-timestamp",  hh.get("x-ca-timestamp").toString()).put("x-ca-key", hh.get("x-ca-key").toString()).put("x-ca-nonce", hh.get("x-ca-nonce").toString()).map();
                    String res = post("https://172.17.0.21:4433/api/v2/externalUser/create", hh.get("body").toString(), head);
                    System.out.println("新增"+res);
                    userInfoService.updateById(userInfo);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    continue;
                }
            }
        }
        return data;
    }

    public static String sendRequest(String url, String json) throws IOException {
        System.err.println("json:" + json);
        long start = System.currentTimeMillis();
        URL object = new URL(url);
        HttpURLConnection con = (HttpURLConnection) object.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setReadTimeout(300000);
        con.setConnectTimeout(300000);
        con.setRequestMethod("POST");
        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write(json);
        wr.flush();
        StringBuilder sb = new StringBuilder();
        int HttpResult = 0;
        try {
            HttpResult = con.getResponseCode();
        } catch (java.net.SocketTimeoutException e) {
            throw e;
        }
        System.err.println("-----请求成功-----");
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        con.getInputStream().close();
        wr.close();
        long end = System.currentTimeMillis() - start;
        System.err.println("消耗时间:" + end);
        return sb.toString();
    }

    public static String post(String url, String json, Map<Object, Object> heard) throws Exception {
        System.err.println("json:" + json);
        long start = System.currentTimeMillis();
        URL object = new URL(url);
        trustAllHttpsCertificates();
        HttpsURLConnection con = (HttpsURLConnection) object.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        heard.forEach((k, v) -> con.setRequestProperty(k.toString(), v.toString()));
        con.setReadTimeout(300000);
        con.setConnectTimeout(300000);
        con.setRequestMethod("POST");
        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write(json);
        wr.flush();
        StringBuilder sb = new StringBuilder();
        int HttpResult = 0;
        try {
            HttpResult = con.getResponseCode();
        } catch (java.net.SocketTimeoutException e) {
            System.err.println("-----失败-----");
            throw e;
        }
        System.err.println("-----请求成功-----");
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        con.getInputStream().close();
        wr.close();
        long end = System.currentTimeMillis() - start;
        System.err.println("消耗时间:" + end);
        System.out.println("返回數據"+sb);
        return sb.toString();
    }

    */
/**
     * 设置 https 请求
     * @throws Exception
     *//*

    private static void trustAllHttpsCertificates() throws Exception {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String str, SSLSession session) {
                return true;
            }
        });
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                .getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc
                .getSocketFactory());
    }


    //设置 https 请求证书
    static class miTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

    }

}*/
